import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

@WebServlet("/nanny-profile")
@MultipartConfig(maxFileSize = 2 * 1024 * 1024) // 最大文件大小2MB
public class NannyProfileServlet extends HttpServlet {

    // 数据库连接信息
    private static final String DB_URL = "jdbc:mysql://localhost:3306/baomu?useUnicode=true&characterEncoding=UTF-8&useSSL=false&allowPublicKeyRetrieval=true";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "123456"; // 替换为您的MySQL密码

    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            System.out.println("MySQL JDBC驱动已成功加载");
        } catch (ClassNotFoundException e) {
            System.err.println("无法加载MySQL JDBC驱动");
            e.printStackTrace();
            throw new RuntimeException("无法加载数据库驱动", e);
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 设置字符编码
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        // 检查用户是否登录且是保姆角色
        HttpSession session = request.getSession();
        Integer userId = (Integer) session.getAttribute("userId");
        Integer userRole = (Integer) session.getAttribute("userRole");

        if (userId == null) {
            response.sendRedirect("login.jsp");
            return;
        }

        if (userRole != 1) { // 1表示保姆角色
            response.sendRedirect("access-denied.jsp");
            return;
        }

        // 获取表单数据 - 与数据库字段完全对应
        String b_name = request.getParameter("b_name");
        String b_experience = request.getParameter("b_experience");
        String b_type = request.getParameter("b_type");
        String b_health = request.getParameter("b_health");
        String b_price_str = request.getParameter("b_price");
        String b_description = request.getParameter("b_description");
        Part b_photo_part = request.getPart("b_photo");

        // 验证输入
        if (b_name == null || b_name.trim().isEmpty() ||
                b_experience == null || b_experience.trim().isEmpty() ||
                b_type == null || b_type.trim().isEmpty() ||
                b_health == null || b_health.trim().isEmpty() ||
                b_price_str == null || b_price_str.trim().isEmpty() ||
                b_description == null || b_description.trim().isEmpty()) {

            response.sendRedirect("nanny-profile.jsp?error=请填写所有必填字段");
            return;
        }

        float b_price = Float.parseFloat(b_price_str);
        String b_photo_path = null;

        // 处理照片上传
        if (b_photo_part != null && b_photo_part.getSize() > 0) {
            String fileName = getFileName(b_photo_part);

            if (fileName != null && !fileName.isEmpty()) {
                String uploadDir = getServletContext().getRealPath("/uploads");

                // 确保上传目录存在
                Files.createDirectories(Paths.get(uploadDir));

                // 生成唯一文件名
                String uniqueFileName = userId + "_" + System.currentTimeMillis() + "_" + fileName;
                b_photo_path = "uploads/" + uniqueFileName;

                // 保存文件
                try (InputStream input = b_photo_part.getInputStream()) {
                    Files.copy(input, Paths.get(uploadDir, uniqueFileName), StandardCopyOption.REPLACE_EXISTING);
                }
            }
        }

        // 连接数据库并保存保姆资料
        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD)) {
            System.out.println("数据库连接成功，开始处理保姆资料保存...");

            // 检查是否已有保姆记录
            String checkSql = "SELECT b_id FROM baomu WHERE u_id = ?";
            boolean recordExists = false;
            int b_id = 0;

            try (PreparedStatement checkStmt = conn.prepareStatement(checkSql)) {
                checkStmt.setInt(1, userId);
                try (ResultSet rs = checkStmt.executeQuery()) {
                    if (rs.next()) {
                        recordExists = true;
                        b_id = rs.getInt("b_id");
                    }
                }
            }

            // 插入或更新保姆资料
            String sql;
            if (recordExists) {
                sql = "UPDATE baomu SET b_name = ?, b_experience = ?, b_type = ?, " +
                        "b_health = ?, b_price = ?, b_description = ?" +
                        (b_photo_path != null ? ", b_photo = ?" : "") +
                        " WHERE u_id = ?";
            } else {
                sql = "INSERT INTO baomu (u_id, b_name, b_experience, b_type, b_health, b_price, b_description" +
                        (b_photo_path != null ? ", b_photo" : "") + ") VALUES (?, ?, ?, ?, ?, ?, ?" +
                        (b_photo_path != null ? ", ?" : "") + ")";
            }

            try (PreparedStatement stmt = conn.prepareStatement(sql)) {
                int paramIndex = 1;

                if (recordExists) {
                    stmt.setString(paramIndex++, b_name);
                    stmt.setString(paramIndex++, b_experience);
                    stmt.setString(paramIndex++, b_type);
                    stmt.setString(paramIndex++, b_health);
                    stmt.setFloat(paramIndex++, b_price);
                    stmt.setString(paramIndex++, b_description);

                    if (b_photo_path != null) {
                        stmt.setString(paramIndex++, b_photo_path);
                    }

                    stmt.setInt(paramIndex, userId);
                } else {
                    stmt.setInt(paramIndex++, userId);
                    stmt.setString(paramIndex++, b_name);
                    stmt.setString(paramIndex++, b_experience);
                    stmt.setString(paramIndex++, b_type);
                    stmt.setString(paramIndex++, b_health);
                    stmt.setFloat(paramIndex++, b_price);
                    stmt.setString(paramIndex++, b_description);

                    if (b_photo_path != null) {
                        stmt.setString(paramIndex++, b_photo_path);
                    }
                }

                int rowsAffected = stmt.executeUpdate();

                if (rowsAffected > 0) {
                    System.out.println("保姆资料保存成功");
                    response.sendRedirect("nanny-dashboard.jsp?success=资料保存成功");
                } else {
                    System.out.println("保姆资料保存失败");
                    response.sendRedirect("nanny-profile.jsp?error=资料保存失败");
                }
            }
        } catch (SQLException e) {
            System.err.println("数据库错误: " + e.getMessage());
            e.printStackTrace();
            response.sendRedirect("nanny-profile.jsp?error=数据库错误: " + e.getMessage());
        }
    }

    // 兼容Tomcat 7的文件名获取方法
    private String getFileName(Part part) {
        String contentDisp = part.getHeader("content-disposition");
        String[] tokens = contentDisp.split(";");
        for (String token : tokens) {
            if (token.trim().startsWith("filename")) {
                String fileName = token.substring(token.indexOf("=") + 1).trim();
                fileName = fileName.replace("\"", "");
                return fileName;
            }
        }
        return "";
    }
}